<template>
    <div class="ele-design-body" ref="bformbody">
        <div class="ele-design-body-items" :class="[ pageTheme ]" :style="pageStyle" ref="appViewBody">
            <div class="jzl-page" style="height:100%" v-if="currentPage && currentPage.type === 1">
                <grid-layout ref="gridLayout"
                             :layout.sync="items"
                             :col-num="layoutColNum"
                             :row-height="rowHeight"
                             :is-draggable="!isView"
                             :is-resizable="!isView"
                             :is-mirrored="false"
                             :vertical-compact="true"
                             :margin="layoutMargin"
                             :use-css-transforms="true">
                    <grid-item v-for="(item, index) in items"
                               :x="item.x"
                               :y="item.y"
                               :w="item.w"
                               :h="item.h"
                               :i="item.i"
                               :key="item.page_item_code">
                        <page-item-proxy :item="item" :items="items" :is-design="true" :vars="dataset.state"
                                      :current-item="currentItem" :index="index" :key="index"
                                      @selectItem="handleSelectItem" @itemEnter="handleItemEnter" @itemLeave="handleItemLeave"></page-item-proxy>
                    </grid-item>
                </grid-layout>
            </div>

            <div v-else class="jzl-page-body">
                <template v-for="(item, index) in items">
                    <page-item-proxy :item="item" :is-h5="isH5" :items="items" :vars="dataset.state"
                                  :current-item="currentItem" :index="index" :key="index"
                                  @selectItem="handleSelectItem" @itemEnter="handleItemEnter" @itemLeave="handleItemLeave"></page-item-proxy>
                </template>
            </div>
        </div>
    </div>
</template>
<script>
    import { mapState, mapActions } from 'vuex';
    import _            from 'lodash';
    import ELE_TYPES_Fn from '../ele/ele-types';
    import mutil        from '../../utils/mutil';
    import { PageBase } from 'jzl-web-components';
    import PageItemProxy from './page-item-proxy';

    export default {
        props: [ 'inPageId', 'appId' ],
        extends: PageBase,
        data() {
            return {
                projectId: null,
                designPageId: null,
                iAppId: null,
                loading: false,
                ready: false,
                currentItem: {},
                items: [],
                currentPage: {},
                isH5: true,
                currentItems: [],

                dataset: {
                    state: {},
                    items: {}
                },
                // dyncComps: {},

                watchVarStop: null,
            }
        },
        components: {
            PageItemProxy
        },
        async mounted () {

        },
        computed: {
            ...mapState([
                'loginUser',
                'project',
                'dyncComps'
            ]),
            pageTheme() {
                return _.get(this.currentPage, "style.setting.theme") || "";
            },
            pageStyle() {
                return this.$putils.getStyle(this.currentPage, "style");
            },
        },
        watch: {
            inPageId(val) {
                this.init();
            },
        },
        methods: {
            ...mutil,
            ...mapActions([
                'setDyncComps'
            ]),
            async init() {
                this.designPageId = this.inPageId;
                this.iAppId = this.appId;
                this.projectId = _.get(this.project, 'project_id');

                this.reset();
                await this._refresh(true);

                await jzlJUtils.Page.loadJs(this.currentPage, jzlJUtils.PAGE_TYPE.DETAIL);

                await this.initPageVars(this.currentPage);

                this.currentItems = this.items;

                this.$nextTick(() => {
                    this.watchLater();
                    this.ready = true;
                    this.$emit("ready",this.currentPage)
                });
            },
            watchLater() {
                if(this.watchVarStop && typeof this.watchVarStop === 'function') this.watchVarStop();

                let watchVarStop = this.$watch('currentPage.vars', (val) => {
                    this.initPageVars(this.currentPage)
                }, { deep: true });

                this.watchVarStop = watchVarStop;
            },
            handleItemStateChange(data) {
                let item = _.get(data, "item");
                let state = _.get(data, "state");
                let alias = _.get(item, "alias");
                let code = alias || _.get(item, "page_item_code");

                this.$set(this.dataset, `items.${ code }`, state);
                this.dataset.items[ code ] = state;
            },
            async _parse(page) {
                let pageType = _.get(this.page, 'type');
                let ELE_TYPES = ELE_TYPES_Fn();

                if(pageType === 2) {   // h5
                    ELE_TYPES = ELE_TYPES_Fn('H5');
                }

                if(page && page.items) {
                    for(let i = 0; i < page.items.length; i++) {
                        let it = page.items[ i ];

                        it.i = it.page_item_code;
                        // it.box_style = this.$putils.getInitMixStyle(it.box_style);
                        // it.ele_style = this.$putils.getInitMixStyle(it.ele_style);

                        if(it.is_dynccomp === 1) {
                            if(it.comp_lib && it.component) {
                                let key = `${ it.comp_lib }-${ it.component }`;
                                // let def = this.dyncComps[ key ];

                                let compInfo = this.dyncComps[ key ];
                                let def = _.get(compInfo, "comp_def");

                                if(!def) {
                                    compInfo = await this.$japi.comp.getCompByName(it.component, it.comp_lib);
                                    def = _.get(compInfo, "comp_def");

                                    // this.dyncComps[ key ] = def;
                                    this.setDyncComps(compInfo);
                                    // this.dyncComps[ key ] = def;
                                }
                                if(def) {
                                    let newItem = _.defaultsDeep(it, _.cloneDeep(def));
                                    _.assignIn(it, newItem);
                                }
                            }
                        } else {
                            let component = _.get(it, "component");
                            let box_style = _.get(it, "box_style");
                            let ele_style = _.get(it, "ele_style");

                            let itemDef = _.get(ELE_TYPES, component);
                            let boxDft = _.get(itemDef, "box_style");
                            let eleDft = _.get(itemDef, "ele_style");

                            if(boxDft) {
                                it.box_style = _.defaultsDeep(box_style, boxDft);
                            }

                            if(eleDft) {
                                it.ele_style = _.defaultsDeep(ele_style, eleDft);
                            }

                            if(!it.subs || !_.isArray(it.subs)) it.subs = [];
                        }
                    }
                }

                return page;
            },
            reset() {
                this.currentItem = {};
            },
            async refresh() {}, // 兼容 Page Base 重复调用的问题
            async _refresh(isInit = false) {
                this.loading = true;

                let page = {};

                if(this.designPageId) {   // 修改
                    page = await this.$japi.page.getPage(this.designPageId);
                }

                this.currentPage = await this._parse(page);
                this.items = this.currentPage.items || [];

                this.loading = false;
            },
            handleSelectItem(data) {
                this.currentItem = _.get(data, 'item');
                this.currentItems = _.get(data, 'items');
                this.$emit("selectItem", data);
            },
            getIndex() {
                let itemCode = _.get(this.currentItem, 'page_item_code');
                if(!itemCode) return -1;
                return _.findIndex(this.currentItems, { page_item_code: itemCode });
            },
            copy() {
                let idx = this.getIndex();

                if(idx < 0) return;

                let orig = this.currentItems[ idx ];
                let code = this.$utils.getNanoid(10);
                let citem = _.defaultsDeep({
                    page_item_code: code,
                    alias: this._getAlias(code),
                    project_id: this.projectId,
                    module_name: code,
                    i: code
                }, orig);   // _.merge({}, this.items[index]);

                if(citem.options && citem.options.length) {
                    for(let i = 0; i < citem.options.length; i++) {
                        citem.options[i].fio_code = this.$utils.getNanoid(10);
                    }
                }

                this.currentItems.splice(idx + 1, 0, citem);
            },
            handleItemEnter(pageItemCode) {
                this.hoverItemCode = pageItemCode;
            },
            handleItemLeave(pageItemCode) {
                if(pageItemCode === this.hoverItemCode) {
                    this.hoverItemCode = '';
                }
            },
        }
    };
</script>
